package com.zxt.dao.impl;

import com.zxt.dao.CarDao;
import com.zxt.domain.Cart;
import com.zxt.util.DataSourceUtils;
import com.zxt.util.StringUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

public class CartDaoImpl implements CarDao {
    private QueryRunner queryRunner=new QueryRunner(DataSourceUtils.getDataSource());
    @Override
    public void insert(Cart cart) {
        String sql=" insert into tb_cart (id,pid,num,money) values(?,?,?,?) ";
        Object[] params={cart.getId(),cart.getPid(),cart.getNum(),cart.getMoney()};
        try {
            queryRunner.update(sql,params);
        } catch (SQLException e) {
           throw new RuntimeException(e);
        }
    }

    @Override
    public Cart select(Integer uid, Integer goods_id) {
        String sql=" select * from tb_cart where id=? and pid=?";
        try {
            return queryRunner.query(sql,new BeanHandler<>(Cart.class),uid,goods_id);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void update(Cart cart) {
        String sql=" update tb_cart set num=?,money=? where id=? and pid=? ";
        Object[] params={cart.getNum(),cart.getMoney(),cart.getId(),cart.getPid()};
        try {
            queryRunner.update(sql,params);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<Cart> select(Integer uid) {
        String sql=" select * from tb_cart where id=? ";
        try {
            return queryRunner.query(sql,new BeanListHandler<>(Cart.class),uid);
        } catch (SQLException e) {
            throw new RuntimeException(e);

        }
    }

    @Override
    public void delete(Integer uid, int goods_id) {
        String sql=" delete from tb_cart where id=? and pid=? ";
        try {
            queryRunner.update(sql,uid,goods_id);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void delete(Integer uid) {
        Connection connection = DataSourceUtils.getConnection();
        String sql=" delete from tb_cart where id=? ";
        try {
            queryRunner.update(sql,uid);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
         DataSourceUtils.closeAll(null,null,connection);
        }
    }
}
